package com.example.traning.mall.framework.security.core.filter;

import cn.hutool.core.util.StrUtil;
import com.example.traning.mall.framework.common.pojo.R;
import com.example.traning.mall.framework.common.util.servlet.ServletUtils;
import com.example.traning.mall.framework.security.core.service.OAuth2TokenApi;
import com.example.traning.mall.framework.web.core.GlobalExceptionHandler;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author lei yu
 * @since 2024/10/14
 */
@RequiredArgsConstructor
@Slf4j
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final static String TOKEN_HEADER = "Authorization";

    private final GlobalExceptionHandler globalExceptionHandler;
    private final OAuth2TokenApi oauth2TokenApi;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 尝试接收客户端的请求中携带的JWT数据
        String token = request.getHeader(TOKEN_HEADER);
        if (StrUtil.isNotEmpty(token)) {
            try {
                oauth2TokenApi.checkAccessToken(token);
            } catch (Throwable ex) {
                R result = globalExceptionHandler.exceptionHandler(ex);
                ServletUtils.writeJson(response, result);
                return;
            }
            log.info("验证JWT完毕，已经向 SecurityContext 中存入认证信息，过滤器将放行");
        }
        // 继续传递
        filterChain.doFilter(request, response);
    }
}
